﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WebDictionary;
using System.Diagnostics;
using System.Threading;

namespace EDBuilder
{
    public partial class StartForm : Form
    {
        string strWDFileName = "";
        Pinyinutil pyTable = null;
        string ErrMessage = "";
        bool IsDirty = false;
        bool IsLoad = false;
        public StartForm()
        {
            InitializeComponent();

        }
        //=============new...
        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (IsDirty)
                {

                    if (!DirtyProcess())
                    {//if users cancel the saving
                        return;
                    }
                }
                WebDicManage wdm = new WebDicManage();
                wdm.NewWebDic();
                // insert a example of a word
                
                WDWord wdw = new WDWord();
                wdw.strWord = "词条示例一";
                wdw.strPinYin = "ci2 tiao2 shi4 li4 yi1";

                wdm.InsertAWord(wdw);

                RestoreToUI(wdm);

                DicGuid.Text = "{" + Guid.NewGuid().ToString().ToUpper() + "}";
                SaveMenuItem.Enabled = true;
                SaveAsMenuItem2.Enabled = true;
                splitContainer1.Visible = true;
                strWDFileName = "";
                this.Text = "微软拼音输入法2010 扩展词典工具--";

                wdm.Close();
                IsDirty = false;
                IsLoad = true;

            }
            catch (Exception eee)
            {
                MessageBox.Show(string.Format("新建扩展词典错\n %s\n", e.ToString()));
                return;
            }


        }
        //==============open...
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {

                if (!DirtyProcess())
                {
                    return;
                }

                OpenFileDialog ofd = new OpenFileDialog();
                //openFileDialog.InitialDirectory=\"c:\\\\\";//注意这里写路径时要用c:\\\\而不是c:\\ 
                ofd.Filter = @"扩展词典|*.dctx|all files|*.*";
                ofd.RestoreDirectory = true;
                ofd.FilterIndex = 1;
                ofd.ValidateNames = true;

                ofd.CheckPathExists = true;

                ofd.CheckFileExists = true;


                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    WebDicManage wdm = new WebDicManage();

                    wdm.LoadWebDic(ofd.FileName);
                    RestoreToUI(wdm);
                    SaveMenuItem.Enabled = true;
                    SaveAsMenuItem2.Enabled = true;
                    splitContainer1.Visible = true;
                    strWDFileName = ofd.FileName;
                    this.Text = "微软拼音输入法2010 扩展词典工具--" + strWDFileName;
                    wdm.Close();
                    IsLoad = true;
                    IsDirty = false;
                }
            }
            catch (Exception eee)
            {
                MessageBox.Show(string.Format("打开扩展词典错！\n %s\n", e.ToString()));
                return;
            }

        }
        //=================exit...
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
    
           if (!DirtyProcess())
               return;
   
            this.Close();
        }

        private void StartForm_Load(object sender, EventArgs e)
        {
            SaveAsMenuItem2.Enabled = false;
            SaveMenuItem.Enabled = false;
            splitContainer1.Visible = false;
            IsLoad = false;

            TitleLbl.Left = (this.Width - TitleLbl.Width) / 2;
            TitleLbl.Top = 100;
            

            IntroductionLbl.Left = (this.Width - IntroductionLbl.Width) / 2;
            IntroductionLbl.Top = TitleLbl.Bottom + 20;

            //Text = (string) 
        }
        //===================save
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            try
            {
                if (strWDFileName == "")
                {
                    SaveFileDialog sfd = new SaveFileDialog();
                    //openFileDialog.InitialDirectory=\"c:\\\\\";//注意这里写路径时要用c:\\\\而不是c:\\ 
                    sfd.Filter = @"扩展词典|*.dctx|all files|*.*";
                    sfd.RestoreDirectory = true;
                    sfd.FilterIndex = 1;
                    sfd.ValidateNames = true;
                    sfd.CheckPathExists = true;
                    sfd.AddExtension = true;
                    sfd.OverwritePrompt = true;
                    if (sfd.ShowDialog() != DialogResult.OK)
                    {
                        return;
                    }
                    strWDFileName = sfd.FileName;
                }
                WebDicManage wdm = new WebDicManage();
                wdm.NewWebDic();
                SaveToXML(wdm);
                wdm.SaveWebDic(strWDFileName);
                this.Text = "微软拼音输入法2010 扩展词典工具--" + strWDFileName;
                IsDirty = false;
            }
            catch (Exception eee)
            {
                MessageBox.Show("保存扩展词典时出错，请过后再试！!", "扩展词典创建", MessageBoxButtons.OK);
            }
        }
        //===================save as...
        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog sfd = new SaveFileDialog();
                //openFileDialog.InitialDirectory=\"c:\\\\\";//注意这里写路径时要用c:\\\\而不是c:\\ 
                sfd.Filter = @"扩展词典|*.dctx|all files|*.*";
                sfd.RestoreDirectory = true;
                sfd.FilterIndex = 1;
                sfd.ValidateNames = true;
                sfd.CheckPathExists = true;
                sfd.AddExtension = true;
                sfd.OverwritePrompt = true;
                if (sfd.ShowDialog() != DialogResult.OK)
                {
                   return;
                }

                WebDicManage wdm = new WebDicManage();
                wdm.NewWebDic();
                SaveToXML(wdm);
                wdm.SaveWebDic(sfd.FileName);
                strWDFileName = sfd.FileName;
                this.Text = "微软拼音输入法2010 扩展词典工具--" + strWDFileName;
                wdm.Close();
                IsDirty = false;
            }
            catch (Exception eee)
            {
                MessageBox.Show(string.Format("打开扩展词典错！\n %s\n", e.ToString()));
                return;
            }

        }


        private void SaveToXML(WebDicManage wdm)
        {
            if (wdm != null)
            {
                CheckForIllegalCrossThreadCalls = false;
                OutputBox.Text = "保存词典...\r\n";
                ProgressBar.Visible = true;

                wdm.SetDictinaryGUID(DicGuid.Text);
                wdm.SetDictinaryVersion(DicVersion.Text);
                wdm.SetDictinarySourceURL(DicHomeURL.Text);

                wdm.SetDictinaryCHSShortname(DicShortName.Text);
                wdm.SetDictinaryCHSLongname(DicLongName.Text);
                wdm.SetDictinaryCHSDescription(DicDescript.Text);
                wdm.SetDictinaryCHSCopyright(DicPublisher.Text);

                wdm.SetDictinaryENGShortname(DicShortNameEn.Text);
                wdm.SetDictinaryENGLongname(DicLongNameEn.Text);
                wdm.SetDictinaryENGDescription(DicDescriptionEn.Text);
                wdm.SetDictinaryENGCopyright(DicPublisherEn.Text);

                ProgressBar.Maximum = WordListView.Rows.Count;
                ProgressBar.Minimum = 0;
                int ierrword = 0;
                for (int i = 0; i < WordListView.Rows.Count; i++)
                {
                    WDWord wdw = GetWordFromView(i);
                    if (wdw != null)
                    {
                        int ret = VerifyAWord(wdw);
                        if (ret != 0)
                        {
                            switch (ret)
                            {

                                case 1: //Chinese word is invalid
                                    OutputBox.Text += string.Format("行: {0} ->({1}): 中文词条无效，忽略！ \r\n ", i + 1, wdw.strWord);
                                    ierrword++;
                                    break;
                                case 2:
                                    OutputBox.Text += string.Format("行: {0} ->({1}): 拼音无效，忽略！ \r\n ", i + 1, wdw.strPinYin);
                                    ierrword++;
                                    break;
                                case 3:
                                    OutputBox.Text += string.Format("行: {0} ->({1}): 词条的汉字个数和拼音数不等，忽略！ \r\n ", i + 1, wdw.strWord + " " + wdw.strPinYin);
                                    ierrword++;
                                    break;
                                case 4:
                                    OutputBox.Text += string.Format("行: {0} ->({1}): 中文词条和拼音都无效，忽略！ \r\n ", i + 1, wdw.strWord + "" + wdw.strPinYin);
                                    ierrword++;
                                    break;
                                case 5:
                                    OutputBox.Text += string.Format("行: {0} ->({1}): 不支持单字词，忽略！\r\n ", i + 1, wdw.strWord + "" + wdw.strPinYin);
                                    ierrword++;
                                    break;
                                default:
                                    OutputBox.Text += string.Format("行: {0} ->({1}): 未知错误，忽略！ \r\n ", i + 1, wdw.strWord + "" + wdw.strPinYin);
                                    ierrword++;
                                    break;
                            }
                        }
                        else
                        {
                            if (!wdm.InsertAWord(wdw))
                            {
                                OutputBox.Text += string.Format("警告: 行{0}->{1} ({2}) 插入词失败，忽略！\r\n", i + 1, wdw.strWord, wdw.strPinYin);
                            }
                        }
                    }
                    ProgressBar.Value = i;
                }
                ProgressBar.Value = 0;
                OutputBox.Text += string.Format("总共 {0} 个词条有错, 在保存词典时被忽略！\r\n", ierrword);
                OutputBox.Text += "==============================\r\nDone! \r\n";

            }
        }

        private bool DirtyProcess()
        {

            if (!IsDirty)
              return true;

            DialogResult dr = MessageBox.Show("修改没有保存，您想保存吗？", "扩展词典创建工具", MessageBoxButtons.YesNoCancel);
            if (dr == DialogResult.Cancel)
                return false;
            if (dr == DialogResult.No)
                return true;

            WebDicManage wdm = new WebDicManage();
            wdm.NewWebDic();
            SaveToXML(wdm);
            if (strWDFileName == "")
            {
                SaveFileDialog sfd = new SaveFileDialog();
                //openFileDialog.InitialDirectory=\"c:\\\\\";//注意这里写路径时要用c:\\\\而不是c:\\ 
                sfd.Filter = @"扩展词典|*.dctx|all files|*.*";
                sfd.RestoreDirectory = true;
                sfd.FilterIndex = 1;
                sfd.ValidateNames = true;
                sfd.CheckPathExists = true;
                sfd.AddExtension = true;
                sfd.OverwritePrompt = true;
                if (sfd.ShowDialog() != DialogResult.OK)
                {
                    return false;
                }
                strWDFileName = sfd.FileName;
            }
            if (wdm.SaveWebDic(strWDFileName))
                IsDirty = false;

            this.Text = "微软拼音输入法2010 扩展词典工具--" + strWDFileName;


            return true;
        }

        private WDWord GetWordFromView(int idx)
        {
            try
            {
                WDWord wdw = new WDWord();
                if (WordListView.Rows[idx].Cells[0].Value != null)
                {
                    wdw.strWord = WordListView.Rows[idx].Cells[0].Value.ToString().Trim();
                }
                if (WordListView.Rows[idx].Cells[1].Value != null)
                {
                    wdw.strPinYin = WordListView.Rows[idx].Cells[1].Value.ToString().Trim();
                }
                return wdw;
            }
            catch (Exception eee)
            {
                return null;
            }

        }
        private void RestoreToUI(WebDicManage wdm)
        {

            if (wdm != null)
            {
                CheckForIllegalCrossThreadCalls = false;
                OutputBox.Text = "加载词典...\r\n";
                ProgressBar.Visible = true;

                
                DicGuid.Text = wdm.GetDictinaryGUID();
                DicVersion.Text = wdm.GetDictinaryVersion();
                DicHomeURL.Text = wdm.GetDictinarySourceURL();

                DicShortName.Text = wdm.GetDictinaryCHSShortname();
                DicLongName.Text = wdm.GetDictinaryCHSLongname();
                DicDescript.Text = wdm.GetDictinaryCHSDescription();
                DicPublisher.Text = wdm.GetDictinaryENGCopyright();

                DicShortNameEn.Text = wdm.GetDictinaryENGShortname();
                DicLongNameEn.Text = wdm.GetDictinaryENGLongname();
                DicDescriptionEn.Text = wdm.GetDictinaryENGDescription();
                DicPublisherEn.Text = wdm.GetDictinaryENGCopyright();

                wdm.GetWordList();
                WordListView.Rows.Clear();

                ProgressBar.Maximum = wdm.GetWordCount();
                ProgressBar.Minimum = 0;
                for (int i = 0; i < wdm.GetWordCount(); i++)
                {
                    WDWord wdw = wdm.GetWord(i);
                    string[] rowll = new string[] { wdw.strWord.Trim(), wdw.strPinYin.Trim() };
                    WordListView.Rows.Add(rowll);
                    ProgressBar.Value = i;
                }
                ProgressBar.Value = 0;
                RowColStatus.Text = string.Format("Row: 0 / {0}", WordListView.Rows.Count);
                OutputBox.Text += "Done!!\r\n";
                IsLoad = true;
            }
        }


        private void WordListpaste()
        {
            //从当前单元格的行开始向下粘贴
            if (WordListView.CurrentCell == null)
                return;
            int insertRowIndex = WordListView.CurrentCell.RowIndex;
            int insertColIndex = WordListView.CurrentCell.ColumnIndex;

            //取得剪贴板的内容，以行分割
            string pasteText = Clipboard.GetText();
            if (string.IsNullOrEmpty(pasteText))
                return;
            pasteText = pasteText.Replace("\r\n", "\n");
            pasteText = pasteText.Replace('\r', '\n');
            pasteText.TrimEnd(new char[] { '\n' });
            string[] lines = pasteText.Split('\n');

            ProgressBar.Maximum = lines.Length;
            ProgressBar.Minimum = 0;

            ProgressBar.Value = 0;

            foreach (string line in lines)
            {

                //使用Tab and ","分割
                string[] vals = line.Split(new char[] { ',', '\t' });
                //检测列数是否一致
                //if (vals.Length - 1 != WordListView.ColumnCount)
                //  throw new ApplicationException("列数不对。");

                DataGridViewRow row = WordListView.Rows[insertRowIndex];
                if (row.IsNewRow == true)
                {
                    WordListView.Rows.Add();
                }
                row = WordListView.Rows[insertRowIndex];
                //设定Header
                //row.HeaderCell.Value = vals[0];
                //设定每个单元格的值
                for (int i = 0; i < (((row.Cells.Count-insertColIndex) >vals.Length) ? vals.Length: (row.Cells.Count-insertColIndex)); i++)
                {
                        row.Cells[i+insertColIndex].Value = vals[i].Trim();
                }

                //向下一行
                insertRowIndex++;
                if (IsLoad)
                    IsDirty = true;

                ProgressBar.Value++;
            }
            ProgressBar.Value = 0;

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (IsLoad)
                IsDirty = true;
        }

        private void splitContainer1_SizeChanged(object sender, EventArgs e)
        {
            if (splitContainer1.SplitterDistance > 330)
                splitContainer1.SplitterDistance = 330;
        }

        private void DeleteContent()
        {
            ProgressBar.Minimum = WordListView.Rows.Count;
            ProgressBar.Minimum = 0;
            //      OutputBox.Text = string.Format("selected rows:{0}", WordListView.SelectedRows.Count);
            this.Cursor = Cursors.WaitCursor;

            foreach (DataGridViewRow r in WordListView.SelectedRows)
            {
                if (!r.IsNewRow)
                {
                    WordListView.Rows.Remove(r);
                }
            }



            for (int i = WordListView.Rows.Count - 1; i >= 0; i--)
            {
                bool isSpace = true;
                if (WordListView.Rows[i].IsNewRow)
                    continue;
                for (int j = 0; j < WordListView.Rows[i].Cells.Count; j++)
                {
                    if (WordListView.Rows[i].Cells[j].Selected)
                    {
                        WordListView.Rows[i].Cells[j].Value = "";
                        ProgressBar.Value = WordListView.Rows.Count - i;

                        // if ((WordListView.Rows[i].Cells[j].Value != null) && (WordListView.Rows[i].Cells[j].Value.ToString().Trim() != ""))
                        //    isSpace = false;
                    }
                    else
                        isSpace = false;
                }
                if (isSpace == true)
                    WordListView.Rows.RemoveAt(i);

            }

            ProgressBar.Value = 0;
            WordListView.ClearSelection();
            this.Cursor = Cursors.Arrow;
        }
        // verify dictionary
        public bool VerifyDictionary()
        {
          string strMess = "";
          
          strMess = OutputBox.Text = "词典验证... \r\n 验证词典是否有效...";
          ShowMessage2OutBox(strMess);

          if (pyTable == null)
              pyTable = new Pinyinutil();
          if (!pyTable.Initialize_done)
          {
              strMess += "开始加载拼音表...！\r\n";
              ShowMessage2OutBox(strMess);
              if (pyTable.InitPinyinTable() == false)
              {
                  strMess += "加载拼音表错误！ \r\n验证停止！";
                  ShowMessage2OutBox(strMess);
                  return false;
              }
          }
          if (!pyTable.Initialize_done)
          {
              strMess += "拼音表加载错误！请试试重启本工具！\r\n";
              ShowMessage2OutBox(strMess);
              return false;
          }
          else
          {
              strMess += "加载拼音表成功！\r\n";
              ShowMessage2OutBox(strMess);
          }

          strMess += "开始验证词典... \r\n";
          ShowMessage2OutBox(strMess);

          ProgressBar.Minimum = 0;
          ProgressBar.Maximum = WordListView.Rows.Count;


            WDWord wdw = new WDWord();
            int ierrword = 0;
          for (int i = 0; i < WordListView.Rows.Count; i++)
          {
              if (WordListView.Rows[i].IsNewRow)
                  continue;
              if (WordListView.Rows[i].Cells[0].Value != null)
              {
                  wdw.strWord = WordListView.Rows[i].Cells[0].Value.ToString().Trim();
              }
              if (WordListView.Rows[i].Cells[1].Value != null)
              {
                  wdw.strPinYin = WordListView.Rows[i].Cells[1].Value.ToString().Trim();
              }
              int ret = VerifyAWord(wdw);
              switch (ret)
              {
                  case 0:// no error
                      break;
                  case 1: //Chinese word is invalid
                      strMess += string.Format("行: {0} ->({1}): 中文词条无效!\r\n ", i + 1, wdw.strWord);
                      ShowMessage2OutBox(strMess);
                      ierrword++;
                      break;
                  case 2:
                      strMess += string.Format("Line: {0} ->({1}): 拼音无效!\r\n ", i + 1, wdw.strPinYin);
                      ShowMessage2OutBox(strMess);
                      ierrword++;
                      break;
                  case 3:
                      strMess += string.Format("Line: {0} ->({1}): 词条的汉字个数和拼音数不等!\r\n ", i + 1, wdw.strWord + " " + wdw.strPinYin);
                      ShowMessage2OutBox(strMess);
                      ierrword++;
                      break;
                  case 4:
                      strMess += string.Format("Line: {0} ->({1}): 中文词条和拼音都无效!\r\n ", i + 1, wdw.strWord + "" + wdw.strPinYin);
                      ShowMessage2OutBox(strMess);
                      ierrword++;
                      break;
                  case 5:
                      strMess += string.Format("Line: {0} ->({1}): 不支持单字词!\r\n ", i + 1, wdw.strWord + "" + wdw.strPinYin);
                      ShowMessage2OutBox(strMess);
                      ierrword++;
                      break;
                  default:
                      break;
              }
              ProgressBar.Value = i;

              if (ierrword > 10)
              {
                  strMess += "太多错误，请先改正!\r\n";
                 ShowMessage2OutBox(strMess);
                  return false;
              }
          }
          ProgressBar.Value = 0;

          strMess += string.Format("总共 {0} 个词有错!\r\n", ierrword);
          strMess += "==============================\r\n验证完成! \r\n";
          
          ShowMessage2OutBox(strMess);

          return ( ierrword <= 0);
        }

        public int VerifyAWord(WDWord wdw)
        {
            if (wdw.strPinYin == "" && wdw.strWord != "")
                return 4;
            if (wdw.strPinYin == "" && wdw.strWord != "")
                return 2;
            if (wdw.strPinYin != "" && wdw.strWord == "")
                return 1;
            if (wdw.strWord.Length == 1)
                return 5;
            string[] columns;
            char[] separator = " ".ToCharArray();

            columns = wdw.strPinYin.Split(separator);

            if (columns.Length != wdw.strWord.Length)
                return 3;
            for (int i = 0; i < wdw.strWord.Length; i++)
            {
                bool bChValid = true;
                if (!pyTable.IsValidChineseChar(wdw.strWord[i]))
                {
                    bChValid = false;
                    return 1;
                }
                else
                {
                    string strPys = pyTable.GetAllPinyinInString(wdw.strWord[i].ToString());
                    if (!strPys.Contains(columns[i]))
                    {
                        return 2;
                    }
                }
            }
            return 0;
        }

        // compile dictionary
        public bool CompileDictionary(string dictName, string outfile)
        {
            if (dictName.Trim() == @"")
            {
                ErrMessage = @"词典名无效!";
                return false;
            }

            CheckForIllegalCrossThreadCalls = false;

            System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo();
            psi.FileName = System.Environment.SystemDirectory + "\\makecab.exe";
            // 
            if (!File.Exists(psi.FileName))
            {
                ErrMessage = "找不到创建工具！";
                return (false);

            }
            if (outfile == "")
            {
                ErrMessage = "没有提供输出文件名！ ";
            }
            psi.Arguments = @"""" + dictName + @""" """ + outfile + @"""";

            //psi.UseShellExecute = true;

            psi.CreateNoWindow = true;
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardInput = true;
            psi.UseShellExecute = false;
            Process p = Process.Start(psi);
            StreamReader reader = p.StandardOutput;
            string line = reader.ReadLine();
            string ttt = OutputBox.Text;

            while (!reader.EndOfStream)
            {
                line = reader.ReadLine();
                OutputBox.Text = ttt + line + "\r\n";
            }

            p.WaitForExit();
            p.Close();

            OutputBox.Text += OutputBox.Text + "创建结束！\r\n";

            return true;

        }
        private void WordListView_KeyDown(object sender, KeyEventArgs e)
        {

            if (sender != null && sender.GetType() == typeof(DataGridView))
            {
              /*  if (Control.ModifierKeys == Keys.Control && e.KeyCode == Keys.C)
                {//copy
                    copyToolStripMenuItem_Click(sender, e);
                    //Clipboard.SetDataObject(WordListView.GetClipboardContent());
                    return;
                }
                */
                if (e.KeyCode == Keys.Delete)
                {
                    DeleteContent();
                }
            }

        }

        
        private void NewGUIDBtn_Click(object sender, EventArgs e)
        {
            DicGuid.Text = "{" + Guid.NewGuid().ToString().ToUpper() + "}";
        }

        private void verifyDictionaryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {

                Cursor = Cursors.WaitCursor;
                VerifyDictionary();
                Cursor = Cursors.Arrow;
            }
            catch (Exception eee)
            {
                MessageBox.Show("验证扩展词典时发生错误，请过后再试！", "扩展词典创建工具", MessageBoxButtons.OK);
            }
            finally
            {
                Cursor = Cursors.Arrow;
            }

        }

        private void genarateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (!VerifyDictionary())
                {
                    OutputBox.Text += "创建词典停止！\r\n";
                    return;
                }
                if (strWDFileName == "")
                {//new file
                    IsDirty = true;
                }
                if (!DirtyProcess())
                    return;

                SaveFileDialog sfd = new SaveFileDialog();
                //openFileDialog.InitialDirectory=\"c:\\\\\";//注意这里写路径时要用c:\\\\而不是c:\\ 
                sfd.Filter = @"扩展词典(*dctxc)|*.dctxc|all files|*.*";
                sfd.RestoreDirectory = true;
                sfd.FilterIndex = 1;
                sfd.ValidateNames = true;
                sfd.CheckPathExists = true;
                sfd.AddExtension = true;
                sfd.OverwritePrompt = true;
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    OutputBox.Text += "开始创建词典...\r\n";

                    if (!CompileDictionary(strWDFileName, sfd.FileName))
                    {
                            OutputBox.Text += ErrMessage + "\r\n";
                    }
                    else
                    {
                        OutputBox.Text += "创建成功!!!\r\n";
                    }

                }
            }
            catch (Exception eee)
            {
                MessageBox.Show(string.Format("打开词典错误！\n %s\n", e.ToString()));
                return;
            }


        }

        private void pinyinToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Thread m_thread;
            OutputBox.Text = "";
            CheckForIllegalCrossThreadCalls = false;
            ProgressBar.Visible = true;
            // this.Cursor = Cursors.WaitCursor;
            m_thread = new Thread(new ThreadStart(PinYinAnnote));
            m_thread.Start();
            //Cursor = Cursors.WaitCursor;
            //PinYinAnnote();
            //Cursor = Cursors.Arrow;

            //Cursor = Cursors.Arrow;
            //ProgressBar.Visible = false;
        }

        // Pinyin Annotation
        private void PinYinAnnote()
        {

            string strMess = "";

            Cursor = Cursors.WaitCursor;
            strMess = OutputBox.Text = "拼音标注... \r\n";

            if (pyTable == null)
                pyTable = new Pinyinutil();
            if (!pyTable.Initialize_done)
            {
                strMess += "开始加载拼音表...!\r\n";
                ShowMessage2OutBox(strMess);
                if (pyTable.InitPinyinTable() == false)
                {
                    strMess += "加载拼音表错! \r\n拼音标注停止!!!";
                    ShowMessage2OutBox(strMess);
                    return;
                }
            }
            if (!pyTable.Initialize_done)
            {
                strMess += "拼音表加载错，不能标注，请试试重启本工具\r\n";
                ShowMessage2OutBox(strMess);
                return;
            }
            else
            {
                strMess += "加载拼音表成功!\r\n";
                ShowMessage2OutBox(strMess);
            }


            strMess += "开始拼音标注...\r\n";
            ShowMessage2OutBox(strMess);

            ProgressBar.Minimum = 0;

            WordListView.Enabled = false;


            ProgressBar.Maximum = WordListView.Rows.Count;

            for (int i = 0; i < WordListView.Rows.Count; i++)
            {
                if (WordListView.Rows[i].IsNewRow)
                    continue;

                if (WordListView.Rows[i].Cells[1].Value ==null || WordListView.Rows[i].Cells[1].Value.ToString().Trim().Length == 0)
                {
                    string pinCands = pyTable.GetPinyin(WordListView.Rows[i].Cells[0].Value.ToString());
                    if (pinCands == "")
                    {
                        strMess += string.Format("警告: 行({0}) ({1}) ->包含非法字符，忽略...\r\n", i, WordListView.Rows[i].Cells[0].Value.ToString());
                        ShowMessage2OutBox(strMess);

                    }
                    else
                    {
                        WordListView.Rows[i].Cells[1].Value = pinCands;
                        if (IsLoad)
                            IsDirty = true;
                    }
                }
                ProgressBar.Value = i;
                /*
                if ( i % 200 == 0)
                {
                    int numdone = (int)(i /200) *200 ;

                    ShowMessage2OutBox(strMess + string.Format("{0:D} / {1:D} done!\r\n",numdone, WordListView.SelectedRows.Count));


                    // OutputBox.Text += OutputBox.Text + string.Format("%d%% done!\r\n", (int)(i / interv) * 5);
                }
                */

            }
            ProgressBar.Value = 0;
            strMess += "拼音标注完成!\r\n";
            ShowMessage2OutBox(strMess);
            Cursor = Cursors.Arrow;
            WordListView.Enabled = true;

        }

        void ShowMessage2OutBox(string strMessage)
        {

            this.OutputBox.Text = strMessage;

            /*
             if (this.OutputBox.InvokeRequired)
             {
                 // It's on a different thread, so use Invoke.
                 SetTextCallback d = new SetTextCallback(SetText);
                 this.Invoke
                     (d, new object[] { strMessage});
             }
             else
             {
                 // It's on the same thread, no need for Invoke
                 this.OutputBox.Text = strMessage;
             }*/

        }
        private void SetText(string text)
        {
            this.OutputBox.Text = this.OutputBox.Text + text;
        }

        private void WordListView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            RowColStatus.Text = string.Format("Row: {0} / {1}", e.RowIndex, WordListView.Rows.Count);
        }

        private void WordListView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (IsLoad)
                IsDirty = true;
        }

        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            WordListView.Rows.Clear();
        }

        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {//Copy

            Clipboard.SetDataObject(WordListView.GetClipboardContent());
        }

        private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
        {//paste
            WordListpaste();
        }

        private void WordListView_ColumnHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (WordListView.CurrentCell.RowIndex < 0 || WordListView.CurrentCell.RowIndex >= WordListView.Rows.Count)
                return;

          //  WordListView.Columns[WordListView.CurrentCell.ColumnIndex].ce= true;
            //WordListView.SelectionMode = DataGridViewSelectionMode.ColumnHeaderSelect;
            
        }

        private void WordListView_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)
        {
            
        }

        private void StartForm_Resize(object sender, EventArgs e)
        {

            TitleLbl.Left = (this.Width - TitleLbl.Width) / 2;
            TitleLbl.Top = 30;

            IntroductionLbl.Left = (this.Width - IntroductionLbl.Width) / 2;
            IntroductionLbl.Top = TitleLbl.Bottom + 20;

        }

        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            copyToolStripMenuItem_Click(sender, e);
            DeleteContent();
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void helpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("IEXPLORE.EXE", "http://www.microsoft.com/downloads/details.aspx?FamilyID=F138DCD4-EDB3-4319-BB69-82784E3EA52F&displaylang=zh-cn");

        }


    }
}
